﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Diagnostics;
using wp8nop.Model;
using Microsoft.Practices.ServiceLocation;
using wp8nop.ViewModel;
using System.Windows.Input;

namespace wp8nop
{
    public partial class SubCategorie : PhoneApplicationPage
    {
        
        public SubCategorie()
        {
            InitializeComponent();
            this.Loaded += SubCategorie_Loaded;
        }

        void SubCategorie_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Debug.WriteLine("Sono entrato");
                if (NavigationContext.QueryString["id"] != null)
                {
                    IDataService _dataService = ServiceLocator.Current.GetInstance<IDataService>();

                    string id = (string)NavigationContext.QueryString["id"];
                    string cat = (string)NavigationContext.QueryString["cat"];

                    Debug.WriteLine("IDCat: " + id);
                    Debug.WriteLine("cat: " + cat);

                    Debug.WriteLine("1 : " + subCategorie.ToString());
                    subCategorie.SelectedItem = null;
                    Debug.WriteLine("2");
                    var catlist = _dataService.GetSubCategorie(cat);
                    subCategorie.ItemsSource = catlist;
                    Debug.WriteLine("3");
                    Debug.WriteLine("subCat: " + catlist.Count.ToString());
                    Debug.WriteLine("4");
                }
                
            }
            catch (Exception ex)
            {

                Debug.WriteLine("Eccezione " + ex.Message);
            }
        }



        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
         base.OnNavigatedTo(e);
        }

        private void subCategorie_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selSubCat = (Categoria) e.AddedItems[0];

            var dettProd = ServiceLocator.Current.GetInstance<ProdottiListViewModel>();
            dettProd.SelectedCategory = selSubCat;
            dettProd.SearchString = "";
            NavigationService.Navigate(new Uri("/ProdottiList.xaml", UriKind.Relative));
        }

        private void Search_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                var dettProd = ServiceLocator.Current.GetInstance<ProdottiListViewModel>();
                dettProd.SearchString = tbSearch.Text.Trim();
                dettProd.SelectedCategory = null;
                NavigationService.Navigate(new Uri("/ProdottiList.xaml", UriKind.Relative));
            }
        }
    }
}